<?php
/**
 * User: hoangnq
 * Date: 11/14/11
 * Time: 6:19 PM
 */
function _build_tree_select($params = array())
{
    $ci =& get_instance();
    $params = array_merge(array(
                               'tree' => array(),
                               'parent_id' => 0,
                               'current_parent' => 0,
                               'current_id' => 0,
                               'level' => 0,
                               'type' => 'pages'
                          ), $params);

    extract($params);

    if (!$tree) {
        if ($objs = $ci->db->select('id, parent, title')->get($type)->result()) {
            foreach ($objs as $obj)
            {
                $tree[$obj->parent][] = $obj;
            }
        }
    }

    if (!isset($tree[$parent_id])) {
        return;
    }

    $html = '';

    foreach ($tree[$parent_id] as $item)
    {
        if ($current_id == $item->id) {
            continue;
        }

        $html .= '<option value="' . $item->id . '"';
        $html .= $current_parent == $item->id ? ' selected="selected">' : '>';

        if ($level > 0) {
            for ($i = 0; $i < ($level * 2); $i++)
            {
                $html .= '&nbsp;';
            }

            $html .= '-&nbsp;';
        }

        $html .= $item->title . '</option>';

        $html .= _build_tree_select(array(
                                                'tree' => $tree,
                                                'parent_id' => (int)$item->id,
                                                'current_parent' => $current_parent,
                                                'current_id' => $current_id,
                                                'level' => $level + 1,
                                                'type' => $type
                                           ));
    }

    return $html;
}

/**
 * Build the html for the admin link tree view
 *
 * @author Hoang Nguyen Quang
 * @access public
 * @param array $link Current navigation link
 * @param array $group_id Group ID of link
 */
function tree_builder($link, $group_id)
{
    if ($link['children']):

        foreach ($link['children'] as $link): ?>

                <li id="<?php echo $group_id.'_'.$link['id']; ?>">
                    <div>
                        <a href="#" rel="<?php echo $group_id . '" alt="' . $link['id'] . '">' . $link['title']; ?></a>
                    </div>
            <?php if ($link['children']): ?>
                    <ol>
                            <?php tree_builder($link, $group_id); ?>
                    </ol>
                </li>
            <?php else: ?>
                </li>
            <?php endif; ?>

        <?php endforeach; ?>

    <?php endif;
}
?>